package com.lw.communication;

/**
 * @author LW
 * @2020/8/18 23:07
 */
public class TestPC2 {

    public static void main(String[] args) {
        TV tv = new TV();
        new Actor(tv).start();
        new Audience(tv).start();
    }
}

//生产者--演员
class Actor extends Thread{
    TV tv;
    public Actor(TV tv){
        this.tv=tv;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 20; i++) {
            if (i%2==0){
                tv.play("复仇者联盟"+(i/2));
            }else {
                tv.play("速度与激情"+(i/2));
            }
        }
    }
}

//消费者--观众
class Audience extends Thread{
    TV tv;
    public Audience(TV tv){
        this.tv=tv;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 20; i++) {
            tv.watch();
        }
    }
}

//产品--节目
class TV{
    //演员表演，观众等待
    //观众观看，演员等待
    String program;//表演的节目
    boolean flag = true;
    //表演
    public synchronized void play(String program)  {
        if (!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了-->"+program);
        //通知观众
        this.notifyAll();
        this.program=program;
        this.flag=!this.flag;
    }

    //观看
    public synchronized void watch()  {
        if (flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观看了==>"+program);
        //通知演员
        this.notifyAll();
        this.flag=!this.flag;
    }

}